package com.itheima.security.springmvc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import java.util.ArrayList;

/**
 * @author Administrator
 * @version 1.0
 **/
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Bean
    public UserDetailsService detailsService() {
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        SimpleGrantedAuthority r1 = new SimpleGrantedAuthority("p1");
        SimpleGrantedAuthority r2 = new SimpleGrantedAuthority("p2");
        ArrayList<GrantedAuthority> objects = new ArrayList<>();
        objects.add(r1);
        objects.add(r2);
        inMemoryUserDetailsManager.createUser(User.withUsername("zhangsan").password("123").authorities(objects).build());
        inMemoryUserDetailsManager.createUser(User.withUsername("lisi").password("123").authorities("p2").build());
        return inMemoryUserDetailsManager;
    }

    @Bean
   public PasswordEncoder passwordEncoder(){
       return NoOpPasswordEncoder.getInstance();
    }

   @Override
   protected void configure(HttpSecurity http) throws Exception {
       http.authorizeRequests()
           .antMatchers("/r/r1").hasAnyAuthority("p1")
           .antMatchers("/r/r2").hasAnyAuthority("p2")
           .antMatchers("/r/**").permitAll()// 所有/r/**的请求都必须要认证通过
           .anyRequest().permitAll()// 除了上面拦截的请求，其余的请求都可以通过
           .and()
           .formLogin()// 允许表单登录
           .successForwardUrl("/login-success");// 登录成功之后，跳转的地址。可以自定义
   }
}
